package com.etymgiko.lyricshere.web;

import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etymgiko.lyricshere.model.Artist;
import com.etymgiko.lyricshere.model.Song;
import com.etymgiko.lyricshere.manager.ArtistManager;
import com.etymgiko.lyricshere.manager.SongManager;

import java.util.List;
import java.util.ArrayList;

/**
 *
 * @author Ivan Holub
 */
public class MainController extends AbstractController {

    private ArtistManager artistManager;

    private SongManager songManager;


    public void setArtistManager(ArtistManager artistManager) {
        this.artistManager = artistManager;
    }

    public void setSongManager(SongManager songManager) {
        this.songManager = songManager;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();

        ModelAndView mav = null;

        String artistCode = UrlParser.parseArtist(requestURI);
        if (artistCode != null) {
            mav = new ModelAndView("artistDetails");
            Artist artist = artistManager.findArtistByCode(artistCode);
            List<Song> songs = songManager.getSongs(artist.getId());
            mav.addObject("artist", artist);
            mav.addObject("songs", songs);
        } else {
            SongUrl songUrl = UrlParser.parseSong(requestURI);
            if (songUrl != null) {
                mav = new ModelAndView("songDetails");
                artistCode = songUrl.getArtistCode();
                String songCode = songUrl.getSongCode();
                Artist artist = artistManager.findArtistByCode(artistCode);
                Song song = songManager.findSongByCode(artist.getId(), songCode);
                mav.addObject("artist", artist);
                mav.addObject("song", song);
            }
        }

        return mav;
    }
}
